<?php
/**
 * @package Autogenerator for Joomla!
 * @version 3.0.0
 * @author Truong Cong Duc <truongcongduc4@gmail.com>
 * @link autogenerator.blogspot.com
 * @copyright (c) 2013, Truong Cong Duc
 * @license GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

class AutogeneratorModelMvcs extends JModelList {

    public function __construct($config = array()) {
        if (empty($config['filter_fields'])) {
            $config['filter_fields'] = array(
                'id', 'am.id',
                'table_id', 'am.table_id',
                'title', 'am.title',
                'type', 'am.type',
                'table_name', 'at.title'
            );
        }

        parent::__construct($config);
    }

    protected function populateState($ordering = null, $direction = null) {
        $app = JFactory::getApplication();

        $search = $this->getUserStateFromRequest($this->context . '.filter.search', 'filter_search');
        $this->setState('filter.search', $search);
        
        $iComponentId = $this->getUserStateFromRequest($this->context . '.filter.component_id', 'filter_component_id');
        $this->setState('filter.component_id', $iComponentId);

        parent::populateState('am.title', 'asc');
    }

    protected function getStoreId($id = '') {
        // Compile the store id.
        $id .= ':' . $this->getState('filter.search');

        return parent::getStoreId($id);
    }

    public function getItems() {
        $aItems = parent::getItems();
        
        foreach($aItems as $iKey => $aItem)
        {
            switch ($aItem->type) {
                case 0:
                    $aItem->type_name = JText::_('COM_AUTOGENERATOR_MVC_FIELD_TYPE_LIST');
                    break;

                case 1:
                    $aItem->type_name = JText::_('COM_AUTOGENERATOR_MVC_FIELD_TYPE_FORM');
                    break;
                
                case 2:
                    $aItem->type_name = JText::_('COM_AUTOGENERATOR_MVC_FIELD_TYPE_ITEM');
                    break;
                
                default:
                    $aItem->type_name = JText::_('COM_AUTOGENERATOR_MVC_FIELD_TYPE_UNKNOWN');
                    break;
            }
        }
        return $aItems;
    }

    protected function getListQuery() {
        $db = $this->getDbo();
        $query = $db->getQuery(true);

        $query->select($this->getState('list.select', 'am.id, am.table_id, am.title, am.type, at.title AS table_name'))
                ->from('#__auto_mvc AS am')
                ->join('LEFT', '#__auto_table AS at ON at.id = am.table_id')
                ->where('at.component_id IN (SELECT id FROM #__auto_component WHERE status = 1)');
        

        // For search.
        $search = $this->getState('filter.search');
        if (!empty($search)) {
            if (stripos($search, 'id:') === 0) {
                $query->where('am.id = ' . (int) substr($search, 3));
            } else {
                $search = $db->Quote('%' . $db->escape($search, true) . '%');
                $query->where('(am.title LIKE ' . $search . ' OR am.type LIKE ' . $search . ')');
            }
        }

        $iComponentId = $this->getState('filter.component_id');
        if (is_numeric($iComponentId) && $iComponentId > 0)
        {
            $query->where('at.component_id = ' . (int) $iComponentId);
        }

        
        // For ordering.
        $orderCol = $this->state->get('list.ordering', 'am.title');
        $orderDirn = $this->state->get('list.direction', 'asc');
        $query->order($db->escape($orderCol . ' ' . $orderDirn));
        
        return $query;
    }
    
    public function deleleAllMVCsByTableId($iTableId) {
        $oDatabase = JFactory::getDbo();
        
        $oQuery = $oDatabase->getQuery(true);
        $oQuery->delete($oDatabase->quoteName('#__auto_mvc'));
        $oQuery->where('table_id = ' . (int) $iTableId);

        $oDatabase->setQuery($oQuery);

        try {
            $bResult = $oDatabase->query();
        } catch (Exception $e) {
            if ($sError = $oDatabase->getErrorMsg()) {
                return $sError;
            }
        }
        return $bResult;
    }

    public function deleleAllMVCsByComponentId($iComponentId) {
        $aAllTables = AutogeneratorHelper::getAllTablesByComponentId($iComponentId);
        
        $oDatabase = JFactory::getDbo();
        
        foreach ($aAllTables as $oTable) {
            $oQuery = $oDatabase->getQuery(true);
            $oQuery->delete($oDatabase->quoteName('#__auto_mvc'));
            $oQuery->where('table_id = ' . (int) $oTable->id);

            $oDatabase->setQuery($oQuery);
            
            try {
                $oDatabase->query();
            } catch (Exception $e) {
                if ($sError = $oDatabase->getErrorMsg()) {
                    return $sError;
                }
            }
        }
        
        return true;
    }
    
}
